package cn.gz.zoomtech.common;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Common {
	// 包含一些公共方法
	public static String getString(String sColName) {
		String sColContent = sColName;
		try {
			if (sColContent == null) {
				sColContent = "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sColContent;
	}

	public static String getString_Null(String sColName) {
		String sColContent = sColName;
		try {
			if (sColContent == null) {
				sColContent = "&nbsp;";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sColContent;
	}

	public static String getObj_Null(Object obj) {
		String sColContent = "";
		try {
			if (obj == null) {
				sColContent = "&nbsp;";
			} else {
				sColContent = obj.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sColContent;
	}

	public static String _getObj_Null(Object obj) {
		String sColContent = "";
		try {
			if (obj != null) {
				sColContent = obj.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sColContent;
	}

	public static String getString_Null_wu(String sColName) {
		String sColContent = sColName;
		try {
			if (sColContent == null) {
				sColContent = "无";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sColContent;
	}

	public String DateToString(java.util.Date date) {
		java.text.DateFormat format1 = new java.text.SimpleDateFormat(
				"yyyy-MM-dd");
		return format1.format(date).toString();
	}

	public String StringToDate_yyyy_mm(String str) {
		return str.substring(0, 4) + "-" + str.substring(4, 6);

	}

	public String StringToDate_yyyy_mm_dd(String str) {
		return str.substring(0, 4) + "-" + str.substring(4, 6) + "-"
				+ str.substring(6, 8);

	}

	// 这里是操作properties文件 //根据key读取value
	public static String readKeyGetValue(InputStream in, String key) {
		Properties props = new Properties();
		try {
			props.load(in);
			String value = props.getProperty(key);
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			return "err";
		}
	}

	public static void readProperties(String filePath) {
		Properties props = new Properties();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(
					filePath));
			props.load(in);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements()) {
				String key = (String) en.nextElement();
				String Property = props.getProperty(key);
				System.out.println(key + Property);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 写入properties信息
	public static void writeProperties(String filePath, String parameterName,
			String parameterValue) {
		Properties prop = new Properties();
		try {
			InputStream fis = new FileInputStream(filePath);
			// 从输入流中读取属性列表（键和元素对）
			prop.load(fis);
			// 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
			// 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
			OutputStream fos = new FileOutputStream(filePath);
			prop.setProperty(parameterName, parameterValue);
			// 以适合使用 load 方法加载到 Properties 表中的格式，
			// 将此 Properties 表中的属性列表（键和元素对）写入输出流
			prop.store(fos, "Update '" + parameterName + "' value");
		} catch (IOException e) {
			System.err.println("Visit " + filePath + " for updating "
					+ parameterName + " value error");
		}
	}

	// 判断是否是数字
	public static boolean isInteger(String s) {
		boolean ko = true;
		if (s == null || s.equals(""))
			return false;
		else {
			for (int i = 0; i < s.length() && ko; i++) {
				if (s.charAt(i) > '9' || s.charAt(i) < '0')
					ko = false;
			}
			return ko;
		}
	}

	public static boolean isIpAdress(String ip) {
		Pattern patt = Pattern
				.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
		Matcher mat = patt.matcher(ip);
		if (mat.matches()) {
			return true;
		}
		return false;
	}

	public static boolean isMobileNumber(String number) {
		if (number.matches("^(1)\\d{10}$")) {
			//	if (number.matches("^(13|15|18)\\d{9}$")) {
				return true;
			}
			return false;
	}

	public static Date StringToDate(String date) {
		Date date1 = new Date();
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date1 = format1.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date1;
	}

	public static int str2Ip(String ip) throws Exception {
		InetAddress address = InetAddress.getByName(ip);
		byte[] bytes = address.getAddress();
		int a, b, c, d;
		a = byte2int(bytes[0]);
		b = byte2int(bytes[1]);
		c = byte2int(bytes[2]);
		d = byte2int(bytes[3]);
		int result = (a << 24) | (b << 16) | (c << 8) | d;
		return result;
	}

	public static int byte2int(byte b) {
		int l = b & 0x07f;
		if (b < 0) {
			l |= 0x80;
		}
		return l;
	}

	public static long ip2long(String ip) throws Exception {
		int ipNum = str2Ip(ip);
		return int2long(ipNum);
	}

	public static long int2long(int i) {
		long l = i & 0x7fffffffL;
		if (i < 0) {
			l |= 0x080000000L;
		}
		return l;
	}

	public static String long2ip(long ip) {
		int[] b = new int[4];
		b[0] = (int) ((ip >> 24) & 0xff);
		b[1] = (int) ((ip >> 16) & 0xff);
		b[2] = (int) ((ip >> 8) & 0xff);
		b[3] = (int) (ip & 0xff);
		String x;
		Integer p;
		p = new Integer(0);
		x = p.toString(b[0]) + "." + p.toString(b[1]) + "." + p.toString(b[2])
				+ "." + p.toString(b[3]);
		return x;
	}
	
	/**
	 * 
	 * @param xml
	 * @param 输入秒
	 * @return 返回相应的时分秒
	 */
	public String parseSecond(Object obj) {
		if(obj != null) {
			java.math.BigDecimal se = (java.math.BigDecimal)obj;
			long time = se.longValue();
			int h = (int)(time/3600);
			int m = (int)((time-h*3600)/60);
			int s = (int)((time-h*3600)%60);
			return h+"小时"+m+"分"+s+"秒";
		}
		return "";
	}
	
	/**
	 * 
	 * @param xml
	 * @param 输入字节数量
	 * @return 返回相应的M或者B
	 */
	public String parseByte(Object obj) {
		if(obj != null) {
			java.math.BigDecimal se = (java.math.BigDecimal)obj;
			long in = se.longValue();
			if(in <= 1024) {
				return (int)in+"B";
			} else if(in/1024 < 1024) {
				
				java.math.BigDecimal b = new java.math.BigDecimal(in/1024.00);
				return b.setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue()+"K";
			} else {
				java.math.BigDecimal b = new java.math.BigDecimal(in/1024.00/1024.00);
				return b.setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue()+"M";
			}
		}
		return "";
	}
	
	
	//在数据库中，已经除以1024了
	public String parseKB(Object obj) {
		if(obj != null) {
			java.math.BigDecimal se = (java.math.BigDecimal)obj;
			long in = se.longValue();
			System.out.println(in);
			if(in <= 1024) {
				return (int)in+"K";
			} else {
				java.math.BigDecimal b = new java.math.BigDecimal(in/1024.00);
				return b.setScale(2,java.math.BigDecimal.ROUND_HALF_UP).doubleValue()+"M";
			}
		}
		return "";
	}
	
	
	/*//定位平台url
	public static String LIA_URL = "http://www.baidu.com";
	//定位平台用户名
	public static String LIA_USERNAME = "test";
	//定位平台密码
	public static String LIA_PASSWORD = "test";*/
	
	public String connectionURL(String xml,String liaurl) {
		String tempDate = "";
		try {
			URL url = new URL(liaurl);
			HttpURLConnection connect = (HttpURLConnection) url
					.openConnection();
			connect.setUseCaches(false);
			connect.setDoInput(true);
			connect.setDoOutput(true);
			connect.setRequestProperty("Content-type",
					"application/octet-stream;charset=UTF-8");
			connect.setRequestMethod("POST");
			
			OutputStream os =  connect.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(os);
			BufferedWriter bw = new BufferedWriter(osw);
			
			bw.write(xml);
			bw.flush();
			bw.close();
			 
			//connect.setRequestProperty("xml", xml);
			//得到url返回的结果
			InputStream inputStream = connect.getInputStream();
			
			//记录是否是最后一个字符
			int flag = 0;
			
			//遍历结果
			while (((flag = inputStream.read()) != -1)) {
				int all = inputStream.available();
				byte[] b = new byte[all];
				inputStream.read(b);
				tempDate += new String(b, "UTF-8");
			}
			
			if (tempDate.trim().equals("")) {
				
				return "返回为空！";
			}
			System.out.println("return:   \n"+tempDate);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return tempDate;
	}
}